package yicheng.dinnertogetherapp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import yicheng.dinnertogetherapp.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class FriendRequestListActivity extends Activity{
	ListView friendRequestList_listView;
	RelativeLayout friend_request_listView_layout;
	LinearLayout friendRequestList_loading_layout, addFriend_loading_layout;

	AmazonClientManager clientManager;

	SharedPreferences local_user_information;
	SharedPreferences.Editor local_user_editor;
	String PREFS_NAME = "LocalUserInfo";


	String PHONE_NUMBER;
	String NICKNAME;
	String AcceptedFriendPhoneNumber;
	String AcceptedFriendNickname;



	int chosenPostion;

	Handler handler;

	HashMap<String, String> friendRequestList;
	/*String[] friendRequestNames, friendRequestNumbers;*/
	ArrayList<String> friendRequestNamesList;
	ArrayList<String> friendRequestNumbersList;


	ArrayAdapter<String> adapter;



	boolean isFriendRequestListLoaded;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		clientManager = new AmazonClientManager();

		setContentView(R.layout.friend_request_list_view);

		overridePendingTransition(R.anim.activity_left_in,R.anim.activity_left_out);

		friendRequestList_loading_layout = (LinearLayout) findViewById(R.id.friendRequestList_loading_view_layout);
		friend_request_listView_layout = (RelativeLayout) findViewById(R.id.friend_request_listView_layout);


		addFriend_loading_layout = (LinearLayout) findViewById(R.id.addFriend_loading_view_layout);
		addFriend_loading_layout.setVisibility(View.INVISIBLE);

		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);


		if (isConnectedToInternet()){
			loadFriendRequestList();
		}
		else{
			Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
		}


		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1){

					//set true when database is loaded 
					isFriendRequestListLoaded = true;
					if (isFriendRequestListLoaded){
						friendRequestList_listView = (ListView) findViewById(R.id.friendRequest_list_listView);

						/*friendRequestNamesList = new ArrayList<String>();
						friendRequestNamesList.addAll(Arrays.asList(friendRequestNames));*/

						adapter = new ArrayAdapter<String>(FriendRequestListActivity.this,
								R.layout.list_view_layout, R.id.listView_item_textView, friendRequestNamesList);
						friendRequestList_listView.setAdapter(adapter);

						friendRequestList_loading_layout.setVisibility(View.INVISIBLE);

						friendRequestList_listView.setOnItemClickListener(new ListView.OnItemClickListener(){

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								// TODO Auto-generated method stub

								AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(FriendRequestListActivity.this);
								dialogBuilder.setTitle("Accept Friend");

								chosenPostion = position;



								AcceptedFriendPhoneNumber = friendRequestNumbersList.get(position);
								AcceptedFriendNickname = friendRequestNamesList.get(position);

								String message = "Do you want to accept friend request from " + AcceptedFriendNickname + " " + "(" + AcceptedFriendPhoneNumber + ")?";
								dialogBuilder.setMessage(message);
								dialogBuilder.setCancelable(true);
								dialogBuilder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which)  {
										// TODO Auto-generated method stub
										if (isConnectedToInternet()){
											addFriend_loading_layout.setVisibility(View.VISIBLE);
											friend_request_listView_layout.setEnabled(false);
											friendRequestList_listView.setEnabled(false);

											updateFriendList();
											dialog.cancel();
										}
										else{

											Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
											dialog.cancel();
										}

									}
								});

								dialogBuilder.setNegativeButton("Decline", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which)  {
										// TODO Auto-generated method stub
										dialog.cancel();
									}
								});

								AlertDialog dialog = dialogBuilder.create();
								dialog.show();




							}

						});
					}

					//set loading spinner invisble when database is loaded


				}


				if (msg.what == 2){
					addFriend_loading_layout.setVisibility(View.INVISIBLE);
					friend_request_listView_layout.setEnabled(true);
					friendRequestList_listView.setEnabled(true);


					adapter.remove(adapter.getItem(chosenPostion));
					adapter.notifyDataSetChanged();
					Toast.makeText(getApplicationContext(), "Add friend successfully!", Toast.LENGTH_SHORT).show();
					/*finish();*/
					/*	overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);*/

				}



			}
		};




	}


	private void loadFriendRequestList(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");

		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						friendRequestList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM);

						friendRequestList.remove("2060000000");
						friendRequestList.remove("Name");


						String [] tempFriendRequestNumbers =  friendRequestList.keySet().toArray(new String[0]);
						String [] tempFriendRequestNames =  friendRequestList.values().toArray(new String[0]);


						/*		friendRequestNumbers = new String[tempFriendRequestNumbers.length];
						friendRequestNames = new String[tempFriendRequestNames.length];*/

						friendRequestNumbersList = new ArrayList<String>();
						friendRequestNamesList = new ArrayList<String>();

						for (int i = 0; i < tempFriendRequestNumbers.length; i++){


							friendRequestNumbersList.add(tempFriendRequestNumbers[i]);



						}

						for (int i = 0; i < tempFriendRequestNames.length; i++){


							friendRequestNamesList.add(tempFriendRequestNames[i]);


						}


						Message msg = Message.obtain();
						msg.what = 1;
						handler.sendMessage(msg);


					}

				}).start();
			}

		});

	}


	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)FriendRequestListActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		//Only for testing
		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();
		/*return  mobile_network.isConnectedOrConnecting();*/
	}


	private void updateFriendList(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub



						friendRequestList.remove(AcceptedFriendPhoneNumber);
						friendRequestList.put("2060000000", "dummyUser");

						SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM);



						SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM, friendRequestList);




						HashMap<String, String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);
						myFriendList.put(AcceptedFriendPhoneNumber, AcceptedFriendNickname);
						SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);
						SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER,  SimpleDB.FRIEND_LIST_ITEM, myFriendList);


						HashMap<String, String> acceptedFriendFriendList = SimpleDB.getAttributesForItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.FRIEND_LIST_ITEM);
						acceptedFriendFriendList.put(PHONE_NUMBER, NICKNAME);
						SimpleDB.deleteItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.FRIEND_LIST_ITEM);

						SimpleDB.updateAttributesForItem(clientManager, AcceptedFriendPhoneNumber,  SimpleDB.FRIEND_LIST_ITEM, acceptedFriendFriendList);


						String myOnlineOrOfflineStatus = SimpleDB.getSingleAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE);

						String friendOnlineOrOfflineStatus = SimpleDB.getSingleAttributesForItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE);


						if (myOnlineOrOfflineStatus.equals("online")){
							HashMap<String, String> friendOnlineFriendList = SimpleDB.getAttributesForItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							friendOnlineFriendList.put(PHONE_NUMBER, NICKNAME);
							SimpleDB.deleteItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							SimpleDB.updateAttributesForItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.ONLINE_FRIEND_LIST_ITEM, friendOnlineFriendList);
						}
						else{
							HashMap<String, String> friendOfflineFriendList = SimpleDB.getAttributesForItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							friendOfflineFriendList.put(PHONE_NUMBER, NICKNAME);
							SimpleDB.deleteItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							SimpleDB.updateAttributesForItem(clientManager, AcceptedFriendPhoneNumber, SimpleDB.OFFLINE_FRIEND_LIST_ITEM, friendOfflineFriendList);
						}


						if (friendOnlineOrOfflineStatus.equals("online")){
							HashMap<String, String> myOnlineFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							myOnlineFriendList.put(AcceptedFriendPhoneNumber, AcceptedFriendNickname);
							SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM, myOnlineFriendList);
						}
						else{
							HashMap<String, String> myOfflineFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							myOfflineFriendList.put(AcceptedFriendPhoneNumber, AcceptedFriendNickname);
							SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM, myOfflineFriendList);
						}



						Message msg = Message.obtain();
						msg.what = 2;
						handler.sendMessage(msg);
					}

				}).start();
			}

		});
	}




	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}



}
